Lecture 1

This lecture taught by of Prof. Cathy Yi-Hsuan Chen focuses on introducing the syntax of python, data types, and data structure.

Specifically, the code can be found in the Github

Outlines


Basic Syntax

  • try basic operations: +, -, , /, %, *, //
a = 5
b = 3
a *= 2  # 10
round(a / b, 4)  # 3.3333

c = '10'
d = '20'
e = c + d  # '1020'
f = int(c) + int(d)  # 30
  • try comparision operations: ==, <, <=, >, >=, !=

Data Structure

List, dictionary,set, tuple are very popular data types in Python universe.

List is a collection which is ordered and changeable. Allows duplicate members

Dictionary is a collection which is unordered, changeable and indexed. No duplicate members

Set is a collection which is unordered and unindexed. No duplicate members

Tuple is a collection which is ordered and unchangeable. Allows duplicate members

More detail can be found here

  • Create a list for a sequence of strings
welcome_list = ['Welcome', 'to', 'Python', 'World.', 'It\'s', 'Amazing']
# using back slash to escape the single quote.

# using for loop to iterate all elements in the list.
for word in welcome_list:
    print(word)

# a string is also an object, using the join method to connect all the words in the list.
welcome_sentence = ' '.join(welcome_list)

# slicing string by indices.
welcome_sliced = welcome_sentence[0:10]
# try changing the indices to negative.

# see other methods of string object, like:
welcome_upper_case = welcome_sentence.upper()
# by using dir() function, or help() function
dir(str)
# or a str instance
dir(welcome_upper_case)
# likewise,
help(str)
  • Formating string object
greeting = 'Hallo'
name = 'Jon'
# using format method
welcome_jon = '{}, {}. '.format(greeting, name.upper()) + welcome_sentence
# using f string, you can write variable name into brackets, directly.
welcome_jon_f = f'{greeting}, {name.upper()}. ' + welcome_sentence
  • Methods for list object, including "append", "insert", "pop", "remove"
natr_language = ['English', 'German', 'Chinese']
prog_language = ['C++', 'Java', 'C#']
# how many elements in a list?
len(natr_language)  # 3
# how many elements in a string?
len(natr_language[0])  # 7

# append() allows you to add 1 element at the end of the list
natr_language.append('Spanish')  # ['English', 'German', 'Chinese', 'Spanish']
# insert() allows you to add 1 element at arbitrary place
prog_language.insert(0, 'Python')  # ['Python', 'C++', 'Java', 'C#']
# extend() allows you to add multiple elements at the end of the list
python = ['python 2.7', 'python 3.6']
prog_language.append(python)  # ['Python', 'C++', 'Java', 'C#', ['python 2.7', 'python 3.6']]
more_language = ['Japanese', 'Korean']
natr_language.extend(more_language)  # ['English', 'German', 'Chinese', 'Spanish', 'Japanese', 'Korean']
# remove() elements
prog_language.remove(python)  # ['Python', 'C++', 'Java', 'C#']
natr_language.pop(-1)  # 'Korean' pops out. ['English', 'German', 'Chinese', 'Spanish', 'Japanese']
del prog_language[-1]  # ['Python', 'C++', 'Java']
# iterate in list
for lang in prog_language:
    print(lang)
# iterate in list with index
for num, lang in enumerate(natr_language):
    print(f'{num}. {lang}')
# list to string
natr_language_str = ', '.join(natr_language)  # 'Spanish, Japanese, German, English, Chinese'
natr_language_new = natr_language_str.split(', ')  # ['Spanish', 'Japanese', 'German', 'English', 'Chinese']
# looping in the list. The basic syntax is:
# [func(ele) for func(ele) in a_list if func(ele)]
# For example:
people = [language + ' People' for language in natr_language_new if language.endswith('ese')]
# Indexing
p = [2,3,5,7,11]
# indexing
p[0] # 2
p[-1] # 11

# sclicing
p[:2] # [2, 3]
p[-3:] # [5, 7, 11]

# appending
p.append(13) # [2, 3, 5, 7, 11, 13]
p.extend([17,19]) # [2, 3, 5, 7, 11, 13, 17, 19]

l = list('hallo') # ['h', 'a', 'l', 'l', 'o']
l.sort() # ['a', 'h', 'l', 'l', 'o']
  • Tuple is immutable
gperson_list = ['Jon Dow', '06-04-2000', 'Male', 'U.S.A']
person_tuple = ('Jon Dow', '06-04-2000', 'Male', 'U.S.A')
person_list[0] = 'Allan Lee'  # ['Allan Lee', '06-04-2000', 'Male', 'U.S.A']
person_tuple[0] = 'Allan Lee'  # tuple' object does not support item assignment
  • Set is a collection which is unordered and unindexed
countries_1 = {'China', 'Korea', 'Japan', 'Turkey', 'Singapore', 'Russia', 'Japan'}
countries_2 = {'UK', 'Germany', 'France', 'Spain', 'Italy', 'Russia', 'Turkey'}

print(countries_1)  # sets will drop duplicated elements automatically
count_inter = countries_1.intersection(countries_2)  # {'Russia', 'Turkey'}
count_1_diff = countries_1.difference(countries_2)  # {'China', 'Japan', 'Korea', 'Singapore'}
count_2_diff = countries_2.difference(countries_1)  # {'France', 'Germany', 'Italy', 'Spain', 'UK'}
countries_new = countries_1.union(countries_2)  # merge two sets into 1 and without duplicates
  • Dictionary is in the form of Key-Value pair
course = {'name':'DEDA', 'unit':1} # {'name': 'DEDA', 'unit': 0}

# accessing
course['unit'] # 0
course['unit'] = 1

# get keys
course.keys() # ['name', 'unit']
course.values() # ['DEDA', 1]
# ATTENTION: Output type varies with version of Python: {'Python2.7': list, 'Python3.7': 'its own data type'}

# adding values
course.update({'lecturers':['Chen','Haerdle']}) # {'lecturers': ['Chen', 'Haerdle'], 'name': 'DEDA', 'unit': 1}

Additional Resources

results matching ""

    No results matching ""